package com.qingcheng.consumer;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.qingcheng.pojo.goods.Goods;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.service.goods.SpuService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//商品索引数据更新
@Service
public class IndexUpdateMessageConsumer implements MessageListener {
    @Reference
    private SpuService spuService;
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public void onMessage(Message message) {
        String spuId = new String(message.getBody());
        Goods goods = spuService.findGoodsById(spuId);
        List<Sku> skuList = goods.getSkuList();

        //封装请求对象
        BulkRequest bulkRequest = new BulkRequest();    //创建批量增加请求

        for (Sku sku : skuList) {
            IndexRequest indexRequest = new IndexRequest("sku","doc",sku.getId());
            Map skuMap = new HashMap();
            skuMap.put("name",sku.getName());
            skuMap.put("image",sku.getImage());
            skuMap.put("brandName",sku.getBrandName());
            skuMap.put("categoryName",sku.getCategoryName());
            skuMap.put("price",sku.getPrice());
            skuMap.put("spuId",sku.getSpuId());
            skuMap.put("createTime",sku.getCreateTime());
            skuMap.put("saleNum",sku.getSaleNum());
            skuMap.put("commentNum",sku.getCommentNum());
            skuMap.put("spec", JSON.parseObject(sku.getSpec(),Map.class));

            indexRequest.source(skuMap);
            bulkRequest.add(indexRequest);
        }
        //获取请求结果
        try {
            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            int status = bulk.status().getStatus();
            System.out.println(status);

            restHighLevelClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
